<?php
/*****************************************************************************
Copyright © 2008 The Regents of the University of Nevada
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/

require_once('../init.php');
header('Content-type: text/javascript');
?>

var enforceBounds = <?php if (Preference::getInstance()->shouldEnforcePanMapBounds()) echo 'true'; else echo 'false'; ?>;
var SVGDocument = null;
var SVGWindow = null;
var SVGRoot = null;

function ResetOrientation(to_what) {
	var vb = document.getElementById("vb"); // from html form
	var zoomOut = document.getElementById("zoomOut");
	var zoomIn = document.getElementById("zoomIn");

	var panSVG = SVGDocumentPan.getElementById("pannedArea");
	var rootSVG = SVGDocumentDrag.getElementById("rootSVG");

	var vbArray = to_what.split(" ");
	rx = parseFloat(vbArray[0]);
	ry = parseFloat(vbArray[1]);
	rw = parseFloat(vbArray[2]);
	rh = parseFloat(vbArray[3]);

	rootViewBox = rx + " " + ry + " " + rw + " " + rh;

	// set vars
	vb.setAttribute("value", rootViewBox);
	zoomOut.style.visibility = "visible";
	zoomIn.style.visibility = "visible";
	rootSVG.setAttribute("viewBox", rootViewBox);
	panSVG.setAttribute("x", rx);
	panSVG.setAttribute("y", ry);
	panSVG.setAttribute("width", rw);
	panSVG.setAttribute("height", rh);

	numDigits = <?php echo Preference::getInstance()->getNumMapCoordinateDigits(); ?>;
	x2 = rx + rw;
	ry = -ry;
	y2 = ry - rh;
	displayCoverage(rx, ry, x2, y2, numDigits);
}

function CenterSelection() {
	// get svg objects
	var rootSVG = SVGDocumentDrag.getElementById("rootSVG");
	var rootViewBox = rootSVG.getAttribute("viewBox");
	var rootViewBoxArray = rootViewBox.split(" ");
	var f = SVGDocumentDrag.getElementById("frame");
	var r = SVGDocumentDrag.getElementById("resizer");

	// get current frame & resizer position
	fx = parseFloat(f.getAttribute("x"));
	fy = parseFloat(f.getAttribute("y"));
	fw = parseFloat(f.getAttribute("width"));
	fh = parseFloat(f.getAttribute("height"));

	rx = parseFloat(r.getAttribute("x"));
	ry = parseFloat(r.getAttribute("y"));
	rw = parseFloat(r.getAttribute("width"));
	rh = parseFloat(r.getAttribute("height"));

	// get current view
	vx = parseFloat(rootViewBoxArray[0]);
	vy = parseFloat(rootViewBoxArray[1]);
	vw = parseFloat(rootViewBoxArray[2]);
	vh = parseFloat(rootViewBoxArray[3]);

	// shrink selection if it is larger than the view
	if (fw > vw) {
		fw = vw * 0.9;
	}
	if (fh > vh) {
		fh = vh * 0.9;
	}

	// account for hemispheres
	if (vx <= 0) { // western
		fx = vx + vw * 0.5 - fw * 0.5;
	}
	if (vx > 0) { // eastern
		fx = vx - vw * 0.5 - fw * 0.5;
	}
	if (vy <= 0) { // northern
		fy = vy + vh * 0.5 - fh * 0.5;
	}
	if (vy > 0) { // southern
		fy = vy - vh * 0.5 - fh * 0.5;
	}

	// set vars
	f.setAttribute("x", fx);
	f.setAttribute("y", fy);
	f.setAttribute("dragx", fx);
	f.setAttribute("dragy", fy);
	f.setAttribute("width", fw);
	f.setAttribute("height", fh);

	r.setAttribute("x", fx + fw - <?php echo Preference::getInstance()->getResizerThickness(); ?>);
	r.setAttribute("y", fy + fh - <?php echo Preference::getInstance()->getResizerThickness(); ?>);
	r.setAttribute("dragx", fx + fw - <?php echo Preference::getInstance()->getResizerThickness(); ?>);
	r.setAttribute("dragy", fy + fh - <?php echo Preference::getInstance()->getResizerThickness(); ?>);
} // CenterSelection


function HighlightMap(map) {
/* Changes the fill of "map" to what "highlightFill" is set to, and sticks the
id of the map in the "currentlyHighlighted" attribute of <g id="outlines">.
Resets that id's fill back to normal when another map is highlighted. */
	var mapGroup = SVGDocumentResults.getElementById('outlines');
	var highlighted = mapGroup.getAttribute("currentlyHighlighted");
	var fill = "none";
	var highlightFill = "yellow";

	if (highlighted != "null") {
		SVGDocumentResults.getElementById(highlighted).setAttribute("fill", fill);
	}
	SVGDocumentResults.getElementById(map).setAttribute("fill", highlightFill);
	mapGroup.setAttribute("currentlyHighlighted", map);
}


function ResultsMapZoom(defaultViewBox) {
	// get vars - html
	var zoom = document.getElementById("zoom");

	// get vars - svg
	var map = SVGDocumentResults.getElementById("svgResults");

	var frame = SVGDocumentResults.getElementById("frame");
	var frameX = parseFloat(frame.getAttribute("x"));
	var frameY = parseFloat(frame.getAttribute("y"));
	var frameW = parseFloat(frame.getAttribute("width"));
	var frameH = parseFloat(frame.getAttribute("height"));

	var viewBox = map.getAttribute("viewBox");
	var viewBoxArray = viewBox.split(" ");
	var vx = parseFloat(viewBoxArray[0]);
	var vy = parseFloat(viewBoxArray[1]);
	var vw = parseFloat(viewBoxArray[2]);
	var vh = parseFloat(viewBoxArray[3]);

	var defaultViewBoxArray = defaultViewBox.split(" ");
	var dvx = parseFloat(defaultViewBoxArray[0]);
	var dvy = parseFloat(defaultViewBoxArray[1]);
	var dvw = parseFloat(defaultViewBoxArray[2]);
	var dvh = parseFloat(defaultViewBoxArray[3]);

	if (viewBox == defaultViewBox) {
		vx = frameX - 0.1;
		vy = frameY - 0.1;
		vw = frameW + 0.2;
		vh = frameH + 0.2;
		zoom.innerHTML = "- Zoom Out";
	}
	else {
		vx = dvx;
		vy = dvy;
		vw = dvw;
		vh = dvh;
		zoom.innerHTML = "+ Zoom In";
	}

	viewBox = vx + " " + vy + " " + vw + " " + vh;

	// set vars
	map.setAttribute("viewBox", viewBox);
}


function ZoomAndPan(direction) {
	// get vars - html
	var vb = document.getElementById("vb"); // from html form
	var zoomInIcon = document.getElementById("zoomIn"); // from html form
	var zoomOutIcon = document.getElementById("zoomOut"); // from html form
	var x1Coverage = parent.document.getElementById("coverageX1");
	var y1Coverage = parent.document.getElementById("coverageY1");
	var x2Coverage = parent.document.getElementById("coverageX2");
	var y2Coverage = parent.document.getElementById("coverageY2");

	// get vars - svg
	var pannedArea = SVGDocumentPan.getElementById("pannedArea");
	var panSVG = SVGDocumentPan.getElementById("panSVG");
	var rootSVG = SVGDocumentDrag.getElementById("rootSVG");

	var rootViewBox = rootSVG.getAttribute("viewBox");
	var rootViewBoxArray = rootViewBox.split(" ");
	var rx = parseFloat(rootViewBoxArray[0]);
	var ry = parseFloat(rootViewBoxArray[1]);
	var rw = parseFloat(rootViewBoxArray[2]);
	var rh = parseFloat(rootViewBoxArray[3]);

	var panViewBox = panSVG.getAttribute("viewBox");
	var panViewBoxArray = panViewBox.split(" ");
	var px = parseFloat(panViewBoxArray[0]);
	var py = parseFloat(panViewBoxArray[1]);
	var pw = parseFloat(panViewBoxArray[2]);
	var ph = parseFloat(panViewBoxArray[3]);

	//var viewBoxAnim = rootSVG.getElementById("viewBoxAnim");

	switch (direction) {
	// hopefully this math is self-explanatory...
	// p* = the pan rect, r* = the pan map viewbox
		case "north":
			if (enforceBounds) {
				if (ry > py && ry - rh * <?php echo Preference::getInstance()->getPanFactor(); ?> > py) {
					ry = ry - rh * <?php echo Preference::getInstance()->getPanFactor(); ?>;
				}
				else ry = py;
			}
			else ry = ry - rh * <?php echo Preference::getInstance()->getPanFactor(); ?>;
			break;
		case "south":
			if (enforceBounds) {
				if (ry + rh < py + ph && ry + rh * 1.25 < py + ph) {
					ry = ry + rh * <?php echo Preference::getInstance()->getPanFactor(); ?>;
				}
				else ry = py + ph - rh;
			}
			else ry = ry + rh * <?php echo Preference::getInstance()->getPanFactor(); ?>;
			break;
		case "east":
			if (enforceBounds) {
				if (rx + rw < px + pw && rx + rw * 1.25 < px + pw) {
					rx = rx + rw * <?php echo Preference::getInstance()->getPanFactor(); ?>;
				}
				else rx = px + pw - rw;
			}
			else rx = rx + rw * <?php echo Preference::getInstance()->getPanFactor(); ?>;
			break;
		case "west":
			if (enforceBounds) {
				if (rx > px && rx - rw * <?php echo Preference::getInstance()->getPanFactor(); ?> > px)
					rx = rx - rw * <?php echo Preference::getInstance()->getPanFactor(); ?>;
				else rx = px;
			}
			else rx = rx - rw * <?php echo Preference::getInstance()->getPanFactor(); ?>;
			break;
		case "in":
			// don't let the view get any smaller than this
			if (rh >= <?php echo Preference::getInstance()->getMapMinCoverageNS(); ?>
			&& rw >= <?php echo Preference::getInstance()->getMapMinCoverageEW(); ?>) {

				zoomOutIcon.style.visibility = "visible";

				rx += rw * 0.125 * <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
				ry += rh * 0.125 * <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
				rw *= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
				rh *= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;

				// disallow zooming past MIN_COVERAGE by hiding the zoom in icon
				if (rh * <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?> <
					<?php echo Preference::getInstance()->getMapMinCoverageNS() * 0.99999; // js float fudge ?>
				|| rw * <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?> <
					<?php echo Preference::getInstance()->getMapMinCoverageEW() * 0.99999; // js float fudge ?>) {
					zoomInIcon.style.visibility = "hidden";
				}
			} // if
			break;
		case "out":
			if (rw <= <?php echo Preference::getInstance()->getMapWidth(); ?>
			|| rh <= <?php echo Preference::getInstance()->getMapHeight(); ?>) { // don't let the view get
													// any larger than this
				zoomInIcon.style.visibility = "visible";
				if (enforceBounds) {
					if (rx - 0.75 < px) rx = px; // left edge
					else rx -= rw * <?php echo 0.1 / (1 - Preference::getInstance()->getScaleFactor()); ?>;

					if (ry - 0.75 < py) ry = py; // top edge
					else ry -= rh * <?php echo 0.1 / (1 - Preference::getInstance()->getScaleFactor()); ?>;

					if (rx + rw + 0.75 > px + pw) { // right edge
						rw /= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
						if (rx - 0.75 < px) rx = px;
						else rx = px + pw - rw;
					}
					else rw /= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;

					if (ry + rh + 0.75 > py + ph) { // bottom edge
						rh /= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
						if (ry - 0.75 < py) ry = py;
						else ry = py + ph - rh;
					}
					else rh /= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
				}
				else {
					rx -= rw * <?php echo 0.1 / (1 - Preference::getInstance()->getScaleFactor()); ?>;
					ry -= rh * <?php echo 0.1 / (1 - Preference::getInstance()->getScaleFactor()); ?>;
					rw /= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
					rh /= <?php echo 1 - Preference::getInstance()->getScaleFactor(); ?>;
				}

				// disallow zooming past DEFAULT_MAP by hiding the zoom out icon
				if (rw > <?php echo Preference::getInstance()->getMapWidth() * 1.00001; // js float fudge ?>
				|| rh > <?php echo Preference::getInstance()->getMapHeight() * 1.00001; // js float fudge
				?>) {
					rx = <?php echo Preference::getInstance()->getMapX(); ?>;
					ry = <?php echo Preference::getInstance()->getMapY(); ?>;
					rw = <?php echo Preference::getInstance()->getMapWidth(); ?>;
					rh = <?php echo Preference::getInstance()->getMapHeight(); ?>;
					zoomOutIcon.style.visibility = "hidden";
				}

			} // if
			break;
	}

	rootViewBox = rx + " " + ry + " " + rw + " " + rh;

	// set vars
	vb.setAttribute("value", rootViewBox);
	rootSVG.setAttribute("viewBox", rootViewBox);
	pannedArea.setAttribute("x", rx);
	pannedArea.setAttribute("y", ry);
	pannedArea.setAttribute("width", rw);
	pannedArea.setAttribute("height", rh);
	//viewBoxAnim.setAttribute("to", rootViewBox);
	//viewBoxAnim.beginElement();


	// get coordinates in order for passing off to displayCoverage()
	numDigits = <?php echo Preference::getInstance()->getNumMapCoordinateDigits(); ?>;
	x2 = rx + rw;
	ry = -ry // correct for inverted coord system relative to Cartesian coords
	y2 = ry - rh;
	displayCoverage(rx, ry, x2, y2, numDigits);
}


function displayCoverage(x1, y1, x2, y2, numDigits) {
	top.document.getElementById("covLongW").innerHTML = x1.toFixed(numDigits);
	top.document.getElementById("covLatS").innerHTML = y1.toFixed(numDigits);
	top.document.getElementById("covLongE").innerHTML = x2.toFixed(numDigits);
	top.document.getElementById("covLatN").innerHTML = y2.toFixed(numDigits);
}


function displaySelection(x1, y1, x2, y2) {
	top.document.getElementById("long_w").value = x1;
	top.document.getElementById("long_e").value = x2;
	top.document.getElementById("lat_s").value = y1;
	top.document.getElementById("lat_n").value = y2;
	top.document.getElementById("printLongW").innerHTML = x1;
	top.document.getElementById("printLongE").innerHTML = x2;
	top.document.getElementById("printLatS").innerHTML = y1;
	top.document.getElementById("printLatN").innerHTML = y2;
}


// Facilitates SVG-HTML communication
// Originally taken from http://svg-whiz.com/svg/interdoc/html-svg.html
// Modified by Alex Dolski 200803
function initEmbed(page) {

	// we branch off using switch() otherwise it will throw js errors.
	switch (page) {
		case 'main':
			var embedDrag = document.getElementById('svgMap');
			var embedPan = document.getElementById('svgPan');

			try { SVGDocumentDrag = embedDrag.getSVGDocument(); }
			catch(exception) {
				/*alert('The GetSVGDocument interface is not supported');*/
			}

			try { SVGDocumentPan = embedPan.getSVGDocument(); }
			catch(exception) {
				/*alert('The GetSVGDocument interface is not supported');*/
			}

			if (SVGDocumentDrag && SVGDocumentDrag.defaultView) {
			// try the W3C standard way first
				SVGWindowDrag = SVGDocumentDrag.defaultView;
				SVGWindowPan = SVGDocumentPan.defaultView;
			}
			else if (embedDrag.window) {
				SVGWindowDrag = embedDrag.window;
				SVGWindowPan = embedPan.window;
			}
			else {
				try {
					SVGDocumentDrag = embedDrag.getWindow();
					SVGDocumentPan = embedPan.getWindow();
				}
				catch(exception) {
					alert('The DocumentView interface is not supported\r\n' +
					'Non-W3C methods of obtaining "window" also failed');
				}
			}
			if (SVGDocumentDrag) {
				SVGRootDrag = SVGDocumentDrag.documentElement;
				SVGRootPan = SVGDocumentPan.documentElement;
			}

			break;

		case 'results':
			var embedResults = document.getElementById('svgResults');

			try { SVGDocumentResults = embedResults.getSVGDocument(); }

			catch(exception) {
				/*alert('The GetSVGDocument interface is not supported');*/
			}

			if (SVGDocumentResults) { // try the W3C standard way first
				SVGWindowResults = SVGDocumentResults.defaultView;
			}
			else if (embedResults.window) {
				SVGWindowResults = embedResults.window;
			}
			else {
				try {
					SVGDocumentResults = embedResults.getWindow();
				}
				catch(exception) {
					alert('The DocumentView interface is not supported\r\n' +
					'Non-W3C methods of obtaining "window" also failed');
				}
			}
			if (SVGDocumentResults) {
				SVGRootResults = SVGDocumentResults.documentElement;
			}
			break;
	} // switch
}


// Following is from Holger Will since ASV3 and O9 do not support getScreenTCM()
// See http://groups.yahoo.com/group/svg-developers/message/50789
function getScreenCTM(doc){
	if(doc.getScreenCTM) { return doc.getScreenCTM(); }

	var root=doc
	var sCTM= root.createSVGMatrix()

	var tr= root.createSVGMatrix()
	var par=root.getAttribute("preserveAspectRatio")
	if (par==null || par=="") par="xMidYMid meet"//setting to default value
	parX=par.substring(0,4) //xMin;xMid;xMax
	parY=par.substring(4,8)//YMin;YMid;YMax;
	ma=par.split(" ")
	mos=ma[1] //meet;slice

	//get dimensions of the viewport
	sCTM.a= 1
	sCTM.d=1
	sCTM.e= 0
	sCTM.f=0

	w=root.getAttribute("width")
	if (w==null || w=="") w=innerWidth

	h=root.getAttribute("height")
	if (h==null || h=="") h=innerHeight

	// Jeff Schiller:  Modified to account for percentages - I'm not
	// absolutely certain this is correct but it works for 100%/100%
	if(w.substr(w.length-1, 1) == "%") {
		w = (parseFloat(w.substr(0,w.length-1)) / 100.0) * innerWidth;
	}
	if(h.substr(h.length-1, 1) == "%") {
		h = (parseFloat(h.substr(0,h.length-1)) / 100.0) * innerHeight;
	}

	// get the ViewBox
	vba=root.getAttribute("viewBox")
	if(vba==null) vba="0 0 "+w+" "+h
	var vb=vba.split(" ")//get the viewBox into an array

	//--------------------------------------------------------------------------
	//create a matrix with current user transformation
	tr.a= root.currentScale
	tr.d=root.currentScale
	tr.e= root.currentTranslate.x
	tr.f= root.currentTranslate.y

	//scale factors
	sx=w/vb[2]
	sy=h/vb[3]

	//meetOrSlice
	if(mos=="slice"){
	s=(sx>sy ? sx:sy)
	}else{
	s=(sx<sy ? sx:sy)
	}

	//preserveAspectRatio="none"
	if (par=="none"){
		sCTM.a=sx//scaleX
		sCTM.d=sy//scaleY
		sCTM.e=- vb[0]*sx //translateX
		sCTM.f=- vb[0]*sy //translateY
		sCTM=tr.multiply(sCTM)//taking user transformations into acount

		return sCTM
	}

	sCTM.a=s //scaleX
	sCTM.d=s//scaleY
	//-------------------------------------------------------
	switch(parX){
	case "xMid":
	sCTM.e=((w-vb[2]*s)/2) - vb[0]*s //translateX

	break;
	case "xMin":
	sCTM.e=- vb[0]*s//translateX
	break;
	case "xMax":
	sCTM.e=(w-vb[2]*s)- vb[0]*s //translateX
	break;
	}
	//------------------------------------------------------------
	switch(parY){
	case "YMid":
	sCTM.f=(h-vb[3]*s)/2 - vb[1]*s //translateY
	break;
	case "YMin":
	sCTM.f=- vb[1]*s//translateY
	break;
	case "YMax":
	sCTM.f=(h-vb[3]*s) - vb[1]*s //translateY
	break;
	}
	sCTM=tr.multiply(sCTM)//taking user transformations into acount

	return sCTM
}
